﻿Imports System.Windows.Forms
Imports Word = Microsoft.Office.Interop.Word

''' <summary>
''' This class provides standard interface to Word documents for loading and saving text 
''' </summary>
''' <remarks>
''' </remarks>
Public Class clsWord

    Declare Function EndTask Lib "user32.dll" (ByVal hWnd As IntPtr) As Integer
    Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
    Declare Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hWnd As IntPtr, ByRef lpdwProcessId As Integer) As Integer
    Declare Function SetLastError Lib "kernel32.dll" (ByVal dwErrCode As Integer) As IntPtr

    Const TempCaption As String = "WRDB WORD"

    Public Event ProgressChanged(ByVal sender As Object, ByVal Percent As Integer)

    ''' <summary>
    ''' Set to true to cancel a long-running operation
    ''' </summary>
    Public Cancel As Boolean

    Private App As Word.Application
    Private Doc As Word.Document

    Private mFileName As String

    ''' <summary>
    ''' Create new workbook and prompt user for name to save as
    ''' </summary>
    Public Sub New()
        Try
            Try
                App = GetObject(, "Word.Application")
            Catch ex As Exception
                Try
                    App = CreateObject("Word.Application")
                Catch ex2 As Exception
                    ErrorMsg("Unable to connect to Microsoft Word application. Please check to make sure it is installed on your computer.")
                End Try
            End Try
            App.Visible = True
            App.Activate()
            App.WindowState = Word.WdWindowState.wdWindowStateNormal
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    ''' <summary>
    ''' Open existing document (or create new one if it does not exist)
    ''' </summary>
    ''' <param name="FileName">Name of existing or new file</param>
    Public Sub New(ByVal FileName As String)
        Me.New()
        Try
            mFileName = FileName

            If My.Computer.FileSystem.FileExists(mFileName) Then 'file exists, load it
                Doc = App.Documents.Open(mFileName)
            Else
                Doc = App.Documents.Add
                App.DisplayAlerts = False
                Doc.SaveAs(mFileName)
                App.DisplayAlerts = True
            End If
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Public Function SelectDocument() As Boolean
        If App.Documents.Count = 0 Then
            WarningMsg("You must first open a Word document and position the cursor where you want all images inserted.")
            Return False
        End If
        With New frmSelect(False)
            .btnSelectAll.Visible = False
            For Each d As Word.Document In App.Documents
                .lstItems.Items.Add(d.Name)
            Next
            .lstItems.SelectedIndex = 0
            .StartPosition = FormStartPosition.CenterScreen
            If .ShowDialog = DialogResult.OK Then
                Doc = App.Documents(.lstItems.Text)
                .Dispose()
                Return True
            Else
                .Dispose()
                Return False
            End If
        End With
    End Function

    Public ReadOnly Property FileName() As String
        Get
            Return mFileName
        End Get
    End Property

    Public Sub Show()
        App.Visible = True
    End Sub

    Public Sub Save()
        Try
            If mFileName = "" Then
                Dim SaveFileDialog As New SaveFileDialog
                With SaveFileDialog
                    .DefaultExt = "docx"
                    .CheckFileExists = True
                    .SupportMultiDottedExtensions = False
                    .Filter = "Word File (*.doc*)|*.doc*"
                    .AddExtension = True
                    .ValidateNames = True
                    If .ShowDialog() = DialogResult.Cancel Then Exit Sub
                    mFileName = .FileName
                End With
                If My.Computer.FileSystem.FileExists(mFileName) Then My.Computer.FileSystem.DeleteFile(mFileName)
                Doc.SaveAs(mFileName)
            Else
                App.DisplayAlerts = False 'so doesn't warn
                Doc.Save()
                App.DisplayAlerts = True
            End If
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    ''' <summary>
    ''' Add image on clipboard to document at current cursor position
    ''' </summary>
    ''' <param name="Caption">Caption to place below image</param>
    Public Sub InsertImage(FileName As String, Optional Caption As String = "")
        Dim shp As Word.InlineShape = Doc.InlineShapes.AddPicture(FileName, , , Doc.ActiveWindow.Selection.Range)
        shp.Range.InsertCaption(Word.WdCaptionLabelID.wdCaptionFigure, " - " & Caption, , Word.WdCaptionPosition.wdCaptionPositionBelow)
        Doc.ActiveWindow.Selection.MoveDown(Word.WdUnits.wdLine, 2)
        Doc.ActiveWindow.Selection.Move(Word.WdUnits.wdParagraph, 1)
        Doc.ActiveWindow.Selection.TypeText(vbCrLf)
    End Sub
End Class
